﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace PookSistener.PO
{
    public partial class frmPurchaseOrder : Form
    {
        private int selectedRow = -1;

        OleDbConnection conn = null;

        List<Customer.Customer> customer = new List<Customer.Customer>();
        List<Product.Product> product = new List<Product.Product>();

        string customerMoney = "";

        List<OrderItem> items = new List<OrderItem>();

        public frmPurchaseOrder()
        {
            InitializeComponent(); 
        }

        private void frmPurchaseOrder_Load(object sender, EventArgs e)
        {
            this.ActiveControl = this.txtInput;

            conn = new OleDbConnection(PookSistener.Properties.Settings.Default.DatabaseConnectionString);
            if (conn.State == ConnectionState.Open)
            {
                conn.Close();
            }

            conn.Open();

            ListAllCustomers();
            ListAllProduct();
        }

        private void ListAllCustomers()
        {
            dataGridCustomerView.AutoGenerateColumns = false;

            OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM Customer", conn);
            adapter.Fill(dataSet1, "Customer");

            dataGridCustomerView.DataSource = dataSet1.Tables["Customer"];
        }

        private void ListAllProduct()
        {
            OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM Product", conn);
            adapter.Fill(dataSet1, "Product");
        }

        private void btnNumber_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
            this.ActiveControl = this.txtInput;
            this.txtInput.Text += btn.TabIndex.ToString();
            this.txtInput.Select(this.txtInput.Text.Length, 0);
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            this.txtInput.Text = "";
            this.ActiveControl = this.txtInput;
        }

        private void btnEnter_Click(object sender, EventArgs e)
        {
            if (txtInput.Text.Trim().Length > 0)
            {
                try
                {
                    DataView dv = new DataView(dataSet1.Tables["Product"]);


                    // Search By Product Id befores

                    dv.RowFilter = "ID='" + txtInput.Text + "'";
                    if (dv.Count > 0)
                    {
                        DataRowView dvv = dv[0];

                        string id = dvv["ID"].ToString();
                        string name = dvv["Name"].ToString();
                        double price = 0;
                        if (txtCustomerName.Tag != null)
                        {
                            int customerId = -1;
                            try
                            {
                                customerId = Convert.ToInt32(txtCustomerName.Tag);

                                string sql = "SELECT Price FROM CustomerProduct WHERE CustomerId=@CustomerId AND ProductId=@ProductId";
                                OleDbCommand cmd = new OleDbCommand(sql, conn);
                                cmd.CommandText = sql;
                                cmd.CommandType = CommandType.Text;

                                cmd.Parameters.Add("@CustomerId", OleDbType.VarChar).Value = txtCustomerName.Tag;
                                cmd.Parameters.Add("@ProductId", OleDbType.VarChar).Value = id;

                                OleDbDataReader reader = cmd.ExecuteReader();
                                if (reader.HasRows)
                                {
                                    reader.Read();
                                    price = reader.GetDouble(0);
                                }

                                reader.Close();

                            }
                            catch (Exception ex)
                            {

                            }
                        }

                        OrderItem item = new OrderItem();
                        item.ID = id;
                        item.Name = name;
                        item.Quantity = 1;
                        item.Price = price;
                        item.Total = (1 * price);

                        items.Add(item);

                        dataGridView1.DataSource = null;
                        dataGridView1.DataSource = items;
                        dataGridView1.AutoGenerateColumns = false;
                        dataGridView1.Invalidate();

                        selectedRow = dataGridView1.Rows.Count - 1;

                        CalculateTotal();
                    }
                    else
                    {
                        // Else Cannot find Product by Product Id
                        dv.RowFilter = "Barcode='" + txtInput.Text + "'";


                        if (dv.Count > 0)
                        {
                            DataRowView dvv = dv[0];

                            string id = dvv["ID"].ToString();
                            string name = dvv["Name"].ToString();

                            double price = 10;
                            if (txtCustomerName.Tag != null)
                            {
                                int customerId = -1;
                                try
                                {
                                    customerId = Convert.ToInt32(txtCustomerName.Tag);

                                    string sql = "SELECT Price FROM CustomerProduct WHERE CustomerId=@CustomerId AND ProductId=@ProductId";
                                    OleDbCommand cmd = new OleDbCommand(sql, conn);
                                    cmd.CommandText = sql;
                                    cmd.CommandType = CommandType.Text;
                                    cmd.Parameters.Clear();

                                    cmd.Parameters.Add("@CustomerId", OleDbType.VarChar).Value = txtCustomerName.Tag;
                                    cmd.Parameters.Add("@ProductId", OleDbType.VarChar).Value = id;

                                    OleDbDataReader reader = cmd.ExecuteReader();
                                    if (reader.HasRows)
                                    {
                                        reader.Read();
                                        price = reader.GetDouble(0);
                                    }

                                    reader.Close();

                                }
                                catch (Exception ex)
                                {

                                }
                            }

                            OrderItem item = new OrderItem();
                            item.ID = id;
                            item.Name = name;
                            item.Quantity = 1;
                            item.Price = price;
                            item.Total = (1 * price);

                            items.Add(item);

                            dataGridView1.DataSource = null;
                            dataGridView1.DataSource = items;
                            dataGridView1.AutoGenerateColumns = false;
                            dataGridView1.Invalidate();

                            selectedRow = dataGridView1.Rows.Count - 1;

                            CalculateTotal();

                        }
                        else
                        {
                            // TODO
                        }
                    }
                    
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error : " + ex.Message);
                }
            }

            this.txtInput.Text = "";
            this.ActiveControl = this.txtInput;
        }


        private void btnChangeQuantity_Click(object sender, EventArgs e)
        {
            if (this.txtInput.Text.Length > 0)
            {
                if (dataGridView1.Rows.Count > 0 && selectedRow > -1)
                {
                    double quantity = 0;

                    try
                    {
                        quantity = Convert.ToDouble(txtInput.Text);

                        OrderItem item = items[selectedRow];
                        item.Quantity = quantity;
                        item.Total = (item.Price * item.Quantity);

                        items.RemoveAt(selectedRow);
                        items.Insert(selectedRow, item);

                        dataGridView1.DataSource = null;
                        dataGridView1.DataSource = items;
                        dataGridView1.Invalidate();

                        dataGridView1.Rows[selectedRow].Selected = true;

                        CalculateTotal();


                        txtInput.Text = "";
                    }
                    catch (Exception ex)
                    {
                        this.txtInput.Text = "";
                    }
                }
            }
           
            this.ActiveControl = this.txtInput;
        }

        private void dataGridView1_Resize(object sender, EventArgs e)
        {
            dataGridView1.Columns[0].Width = (int)(0.4194756554307116 * dataGridView1.Width);
            dataGridView1.Columns[1].Width = dataGridView1.Columns[2].Width = dataGridView1.Columns[3].Width = (int)(0.1872659176029963 * dataGridView1.Width);
        }

        private void btnFinish_Click(object sender, EventArgs e)
        {
            if (dataGridView1.Rows.Count > 0)
            {
                if (txtCustomerName.Text.Trim().Length == 0)
                {
                    MessageBox.Show("กรุณาเลือกลูกค้าให้เรียบร้อย");
                    return;

                }
                lblTotalSummary.Text = lblTotal.Text;
                lblCustomerMoney.Text = "0.00";
                lblChange.Text = "0.00";
                customerMoney = "";

                panelSummary.Left = 100;
                panelSummary.Top = 25;

                panelSummary.Visible = true;

                EorDButton(false);
            }
        }

        private void EorDButton(bool isEnable)
        {
            btnDeleteRow.Enabled = isEnable;
            btn0.Enabled = isEnable;
            btn1.Enabled = isEnable;
            btn2.Enabled = isEnable;
            btn3.Enabled = isEnable;
            btn4.Enabled = isEnable;
            btn5.Enabled = isEnable;
            btn6.Enabled = isEnable;
            btn7.Enabled = isEnable;
            btn8.Enabled = isEnable;
            btn9.Enabled = isEnable;
            btnClose.Enabled = isEnable;
            btnClear.Enabled = isEnable;
            btnFinish.Enabled = isEnable;
            btnChooseProduct.Enabled = isEnable;
            btnCustomerSearch.Enabled = isEnable;
            btnChangePrice.Enabled = isEnable;
            btnChangeQuantity.Enabled = isEnable;
            dataGridView1.Enabled = isEnable;
            txtInput.Enabled = isEnable;
            btnEnter.Enabled = isEnable;
            btnDown.Enabled = isEnable;
            btnUp.Enabled = isEnable;
            btnPoint.Enabled = isEnable;
        }

        private void CalulateChange()
        {
            try
            {
                double net = Convert.ToDouble(lblTotalSummary.Text);
                double cus = Convert.ToDouble(lblCustomerMoney.Text);

                double amount = cus - net;

                lblChange.Text = amount.ToString("#,##0.00");
            }
            catch (Exception ex)
            {
            }
        }

        private void btnChangePrice_Click(object sender, EventArgs e)
        {
            if (this.txtInput.Text.Length > 0)
            {
                if (dataGridView1.Rows.Count > 0 && selectedRow > -1)
                {
                    double price = 0;

                    try
                    {
                        price = Convert.ToDouble(txtInput.Text);

                        OrderItem item = items[selectedRow];
                        item.Price = price;
                        item.Total = (item.Price * item.Quantity);

                        items.RemoveAt(selectedRow);
                        items.Insert(selectedRow, item);

                        dataGridView1.DataSource = null;
                        dataGridView1.DataSource = items;
                        dataGridView1.Invalidate();

                        dataGridView1.Rows[selectedRow].Selected = true;


                        CalculateTotal();

                        txtInput.Text = "";

                    }
                    catch (Exception ex)
                    {
                        this.txtInput.Text = "";
                    }
                }
            }

            this.ActiveControl = this.txtInput;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            CalculateTotal();
            timer1.Enabled = false;
            this.ActiveControl = this.txtInput;
        }

        private void frmPurchaseOrder_ResizeEnd(object sender, EventArgs e)
        {
           
        }

        private void CalculateRow(int currentRow)
        {
            if (dataGridView1.Rows.Count > 0 && currentRow > -1)
            {
                double quantity = Convert.ToDouble(dataGridView1.Rows[currentRow].Cells["colQuantity"].Value);
                double price = Convert.ToDouble(dataGridView1.Rows[currentRow].Cells["colPrice"].Value);
                double total = price * quantity;


                dataGridView1.Rows[currentRow].Cells["colTotal"].Value = total;

                CalculateTotal();
            }

            this.ActiveControl = this.txtInput;
        }

        private void CalculateTotal()
        {
            double Total = 0;
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                double temp = Convert.ToDouble(dataGridView1.Rows[i].Cells["colTotal"].Value);
                Total += temp;
            }

            lblTotal.Text = Total.ToString("#,##0.00");
        }

        private void btnDown_Click(object sender, EventArgs e)
        {
            if (dataGridView1.Rows.Count > 0)
            {
                if (selectedRow > -1)
                {
                    selectedRow++;

                    if (selectedRow > dataGridView1.Rows.Count - 1)
                    {
                        selectedRow = dataGridView1.Rows.Count - 1;
                    }

                    dataGridView1.Rows[selectedRow].Selected = true;
                }
            }

            this.ActiveControl = this.txtInput;
        }

        private void btnUp_Click(object sender, EventArgs e)
        {
            if (dataGridView1.Rows.Count > 0)
            {
                if (selectedRow > -1)
                {
                    selectedRow--;

                    if (selectedRow <= 0)
                    {
                        selectedRow = 0;
                    }

                    dataGridView1.Rows[selectedRow].Selected = true;
                }
            }

            this.ActiveControl = this.txtInput;
        }

        private void btnDeleteRow_Click(object sender, EventArgs e)
        {
            if (dataGridView1.Rows.Count > 0)
            {
                if (selectedRow > -1)
                {

                    items.RemoveAt(selectedRow);

                    dataGridView1.DataSource = null;
                    dataGridView1.DataSource = items;
                    dataGridView1.Invalidate();

                    selectedRow--;
                    if (selectedRow <= 0)
                    {
                        selectedRow = 0;
                    }

                    if (selectedRow > dataGridView1.Rows.Count - 1)
                    {
                        selectedRow = dataGridView1.Rows.Count - 1;
                    }


                    if (dataGridView1.Rows.Count > 0)
                    {
                        dataGridView1.Rows[selectedRow].Selected = true;
                    }
                    else
                    {
                        selectedRow = -1;
                    }

                    CalculateTotal();
                }
            }

            this.ActiveControl = this.txtInput;
        }

        private void btnChooseProduct_Click(object sender, EventArgs e)
        {
            this.ActiveControl = this.txtInput;

            if (this.btnChooseProduct.Tag == null)
            {
                this.btnChooseProduct.Tag = "1";
                return;
            }

            if (this.btnChooseProduct.Tag.Equals("1"))
            {
                this.gbNumberPad.Visible = false;
                this.btnChooseProduct.Tag = "2";
            }
            else
            {
                this.btnChooseProduct.Tag = "1";
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnCustomerSearch_Click(object sender, EventArgs e)
        {
            panelCustomer.Left = dataGridView1.Left;
            panelCustomer.Top = dataGridView1.Top;


            panelCustomer.Visible = true;
        }

        private void btnCloseCustomerPanel_Click(object sender, EventArgs e)
        {
            panelCustomer.Visible = false;
        }

        private void dataGridCustomerView_Resize(object sender, EventArgs e)
        {
            int scrollBarWidth = SystemInformation.VerticalScrollBarWidth + 5;
            int rowHeaderWidth = dataGridView1.RowHeadersWidth + 3;

            int width = dataGridCustomerView.Width - scrollBarWidth;

            int remainingWidth = 0;

            dataGridCustomerView.Columns["tName"].Width = (width - remainingWidth);
        }

        private void dataGridCustomerView_Click(object sender, EventArgs e)
        {
            if (dataGridCustomerView.Rows.Count > 0)
            {
                if (dataGridCustomerView.SelectedRows.Count > 0)
                {
                    DataGridViewRow row = dataGridCustomerView.SelectedRows[0];

                    txtCustomerName.Text = row.Cells["tName"].Value.ToString();
                    txtCustomerName.Tag = row.Cells["ID"].Value.ToString();

                   
                }
            }

            panelCustomer.Visible = false;
        }

        private void btnCloseSummary_Click(object sender, EventArgs e)
        {
            panelSummary.Visible = false;
        }

        private void btnCloseSummary_Click_1(object sender, EventArgs e)
        {
            panelSummary.Visible = false;
            txtInput.Text = "";
            EorDButton(true);
            this.ActiveControl = this.txtInput;
        }

        private void button12_Click(object sender, EventArgs e)
        {
            lblCustomerMoney.Text = "0.00";
            customerMoney = "";

            CalulateChange();
        }

        private void MyButton_Click(object sender, EventArgs e)
        {
            if (lblCustomerMoney.Text.Trim().Length == 0)
            {
                lblCustomerMoney.Text = "0.00";
            }

            Button b = (Button)sender;

            if (customerMoney.Length == 0)
            {
                customerMoney = b.Text;

                double temp = Convert.ToDouble(customerMoney);

                lblCustomerMoney.Text = temp.ToString("#,##0.00");
            }
            else
            {
                customerMoney += b.Text;

                double temp = Convert.ToDouble(customerMoney);

                lblCustomerMoney.Text = temp.ToString("#,##0.00");
            }

            CalulateChange();
        }

        private void button14_Click(object sender, EventArgs e)
        {
            if (customerMoney.IndexOf(".") == -1)
            {
                if (customerMoney.Length == 0)
                {
                    customerMoney = "0.";
                }
                else
                {
                    customerMoney += ".";
                }

                double temp = Convert.ToDouble(customerMoney);

                lblCustomerMoney.Text = temp.ToString("#,##0.00");
            }

            CalulateChange();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OleDbTransaction ts = null;
            try
            {
                

                int order_id = 1;

                // Get Lastest Order Id
                string sql = "SELECT OrderId FROM MyOrder ORDER BY OrderId DESC";

                OleDbCommand cmd = new OleDbCommand();
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = sql;
                cmd.Connection = conn;

                OleDbDataReader reader = cmd.ExecuteReader();

                if (reader.HasRows)
                {
                    reader.Read();

                    int temp = reader.GetInt32(0);
                    order_id = temp + 1;
                }

                reader.Close();

                ts = conn.BeginTransaction();

                // Insert New Order
                sql = "INSERT INTO MyOrder(OrderId, OrderDate, CustomerId, TotalAmount) VALUES(@OrderId, @OrderDate, @CustomerId, @TotalAmount)";

                cmd.CommandType = CommandType.Text;
                cmd.CommandText = sql;
                cmd.Connection = conn;
                cmd.Transaction = ts;
                cmd.Parameters.Clear();

                string today = DateTime.Now.Year.ToString("0000") + "" + DateTime.Now.Month.ToString("00") + "" + DateTime.Now.Day.ToString("00");

                cmd.Parameters.Add("@OrderId", OleDbType.Integer).Value = order_id;
                cmd.Parameters.Add("@OrderDate", OleDbType.VarChar).Value = today;
                cmd.Parameters.Add("@CustomerId", OleDbType.Integer).Value = txtCustomerName.Tag;
                cmd.Parameters.Add("@TotalAmount", OleDbType.Double).Value = lblTotal.Text;

                cmd.ExecuteNonQuery();

                
                // Insert Order Detail
                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {

                    int index = i + 1;

                    DataGridViewRow row = dataGridView1.Rows[i];

                    sql = "INSERT INTO OrderDetail(OrderId, rNo, ProductId, Quantity, Price) VALUES(@OrderId, @rNo, @ProductId, @Quantity, @Price)";

                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = sql;
                    cmd.Connection = conn;
                    cmd.Transaction = ts;
                    cmd.Parameters.Clear();

                    cmd.Parameters.Add("@OrderId", OleDbType.Integer).Value = order_id;
                    cmd.Parameters.Add("@rNo", OleDbType.Integer).Value = index;
                    cmd.Parameters.Add("@ProductId", OleDbType.Integer).Value = row.Cells["colProductId"].Value;
                    cmd.Parameters.Add("@Quantity", OleDbType.Double).Value = row.Cells["colQuantity"].Value;
                    cmd.Parameters.Add("@Price", OleDbType.Double).Value = row.Cells["colPrice"].Value;

                    cmd.ExecuteNonQuery();
                }
                
                ts.Commit();

                MessageBox.Show("บันทึกข้อมูลเรียบร้อยแล้ว");

            }
            catch (Exception ex)
            {
                if (ts != null)
                {
                    ts.Rollback();
                }
                MessageBox.Show("Error : " + ex.Message);
            }
        }

        private void dataGridCustomerView_ClientSizeChanged(object sender, EventArgs e)
        {

        }
    }
}
